package com.ruoyi.wechat.api;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.WxContentSecurityUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.degree.domain.*;
import com.ruoyi.degree.service.*;
import com.ruoyi.wechat.vo.CommentsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wxapi/usercomments")
@Api(tags = "用户讨论API", description = "微信用户讨论相关接口")
public class WechatUserCommentsApi {
    @Autowired
    private IBizCommentsService bizCommentsService;
    @Autowired
    private IBizSchoolsService bizSchoolsService;
    @Autowired
    private IWechatUserService wechatUserService;
    @Autowired
    private IBizCommentsLikeService bizCommentsLikeService;
    @Autowired
    private IWechatNotifyRemindService IWechatNotifyRemindService;


    @ApiOperation("获取评论列表")
    @Anonymous
    @GetMapping("/selectReplys")
    public AjaxResult selectReplys(@RequestParam Long parentId,@RequestParam Long wechatUserId) {
        BizComments comments = new BizComments();
        comments.setParentId(parentId);
        List<BizComments> commentsList = bizCommentsService.selectBizCommentsList(comments);
        List<CommentsVO> commentsVOList = new ArrayList<>();
        for (BizComments bizComments1 : commentsList) {
            CommentsVO commentsVO = new CommentsVO();
            BizSchools bizSchools = bizSchoolsService.selectBizSchoolsById(bizComments1.getObjectId());
            if (bizSchools != null) {
                commentsVO.setSchoolName(bizSchools.getName());
                commentsVO.setSchoolPics(bizSchools.getLogo());
                commentsVO.setIntro(bizSchools.getIntro());
            }
            WechatUser wechatUser = new WechatUser();
            if (bizComments1.getWechatUserId() != null) {
                wechatUser = wechatUserService.selectWechatUserById(bizComments1.getWechatUserId());
            }
            if (wechatUser != null) {
                commentsVO.setNickName(wechatUser.getNickname());
                commentsVO.setAvatarUrl(wechatUser.getAvatarUrl());
            } else {
                commentsVO.setNickName("匿名用户");
            }
            //判断当前用户是否点赞
            BizCommentsLike isLike = new BizCommentsLike();
            isLike.setCommentId(bizComments1.getId());
            isLike.setWechatUserId(wechatUserId);
            List<BizCommentsLike> islikeList = bizCommentsLikeService.selectBizCommentsLikeList
                    (isLike);
            if (islikeList != null && islikeList.size() > 0) {
                commentsVO.setIsLike(1);
            } else {
                commentsVO.setIsLike(0);
            }
            //查询点赞数
            BizCommentsLike like = new BizCommentsLike();
            like.setCommentId(bizComments1.getId());
            List<BizCommentsLike> likeList = bizCommentsLikeService.selectBizCommentsLikeList(like);
            commentsVO.setLikeCount(likeList.size());
            commentsVO.setContent(bizComments1.getContent());
            commentsVO.setTitle(bizComments1.getTitle());
            commentsVO.setCreatedAt(bizComments1.getCreatedAt());
            commentsVO.setId(bizComments1.getId());
            commentsVO.setWechatUserId(bizComments1.getWechatUserId());
            commentsVOList.add(commentsVO);
        }
        return AjaxResult.success(commentsVOList);
    }


    @ApiOperation("评论查找")
    @Anonymous
    @GetMapping("/selectCommentsListByUserId")
    public AjaxResult selectCommentsListByUserId(Long userId) {
        List<CommentsVO> commentsVOList = new ArrayList<>();
        BizComments bizComments = new BizComments();
        bizComments.setWechatUserId(userId);
        List<BizComments> commentsList = bizCommentsService.selectBizCommentsList(bizComments);

        for (BizComments bizComments1 : commentsList) {
            CommentsVO commentsVO = new CommentsVO();
            BizSchools bizSchools = bizSchoolsService.selectBizSchoolsById(bizComments1.getObjectId());
            if (bizSchools != null) {
                commentsVO.setSchoolName(bizSchools.getName());
                commentsVO.setSchoolPics(bizSchools.getLogo());
                commentsVO.setIntro(bizSchools.getIntro());
            }
            WechatUser wechatUser = new WechatUser();
            if (bizComments1.getWechatUserId() != null) {
                wechatUser = wechatUserService.selectWechatUserById(bizComments1.getWechatUserId());
            }
            if (wechatUser != null) {
                commentsVO.setNickName(wechatUser.getNickname());
                commentsVO.setAvatarUrl(wechatUser.getAvatarUrl());
            } else {
                commentsVO.setNickName("匿名用户");
            }
            commentsVO.setContent(bizComments1.getContent());
            commentsVO.setTitle(bizComments1.getTitle());
            commentsVO.setCreatedAt(bizComments1.getCreatedAt());
            commentsVO.setObjectId(bizComments1.getObjectId());
            commentsVO.setId(bizComments1.getId());
            // pics字段转数组
            if (bizComments1.getPics() != null && !bizComments1.getPics().isEmpty()) {
                commentsVO.setPicsArray(bizComments1.getPics().split(","));
            } else {
                commentsVO.setPicsArray(new String[]{});
            }
            commentsVOList.add(commentsVO);
        }
        return AjaxResult.success(commentsVOList);
    }
    @ApiOperation("评论查找")
    @Anonymous
    @GetMapping("/selectCommentsBySchoolId")
    public AjaxResult selectCommentsBySchoolId(@RequestParam Long schoolId,@RequestParam Long wechatUserId) {
        List<CommentsVO> commentsVOList = new ArrayList<>();
        BizComments bizComments = new BizComments();
        bizComments.setObjectId(schoolId);
        bizComments.setType("1");
        List<BizComments> commentsList = bizCommentsService.selectBizCommentsList(bizComments);
        for (BizComments comment : commentsList) {
            CommentsVO commentsVO = new CommentsVO();
            WechatUser wechatUser = new WechatUser();
            if (comment.getWechatUserId() != null) {
                wechatUser = wechatUserService.selectWechatUserById(comment.getWechatUserId());
            }
            if (wechatUser != null) {
                commentsVO.setNickName(wechatUser.getNickname());
                commentsVO.setAvatarUrl(wechatUser.getAvatarUrl());
            } else {
                commentsVO.setNickName("匿名用户");
            }
            if (comment.getPics() != null && !comment.getPics().isEmpty()) {
                commentsVO.setPicsArray(comment.getPics().split(","));
            } else {
                commentsVO.setPicsArray(new String[]{});
            }
            if(wechatUserId>0){
                //判断当前用户是否点赞
                BizCommentsLike isLike = new BizCommentsLike();
                isLike.setCommentId(comment.getId());
                isLike.setWechatUserId(wechatUserId);
                List<BizCommentsLike> islikeList = bizCommentsLikeService.selectBizCommentsLikeList
                        (isLike);
                if (islikeList != null && islikeList.size() > 0) {
                    commentsVO.setIsLike(1);
                } else {
                    commentsVO.setIsLike(0);
                }
            }

            //查询该评论的回复
            BizComments replyComments = new BizComments();
            replyComments.setParentId(comment.getId());
            List<BizComments> replyList = bizCommentsService.selectBizCommentsList(replyComments);
            commentsVO.setReplyCount(replyList.size());
            //查询点赞数
            BizCommentsLike like = new BizCommentsLike();
            like.setCommentId(comment.getId());
            List<BizCommentsLike> likeList = bizCommentsLikeService.selectBizCommentsLikeList(like);
            commentsVO.setLikeCount(likeList.size());
            commentsVO.setContent(comment.getContent());
            commentsVO.setTitle(comment.getTitle());
            commentsVO.setCreatedAt(comment.getCreatedAt());
            commentsVO.setId(comment.getId());
            commentsVO.setWechatUserId(comment.getWechatUserId());
            commentsVO.setObjectId(comment.getObjectId());
            commentsVO.setId(comment.getId());
            commentsVOList.add(commentsVO);
        }
        return AjaxResult.success(commentsVOList);
    }
    @ApiOperation("查询评论详情")
    @Anonymous
    @GetMapping("/getCommentsById")
    public AjaxResult getCommentsById(@RequestParam Long id) {
        BizComments comment = bizCommentsService.selectBizCommentsById(id);
        if (comment == null) {
            return AjaxResult.error("评论不存在，或者已被删除");
        }
        WechatUser wechatUser = null;
        if (comment.getWechatUserId() != null) {
            wechatUser = wechatUserService.selectWechatUserById(comment.getWechatUserId());
        }
        if (wechatUser != null) {
            comment.setNickName(wechatUser.getNickname());
            comment.setAvatarUrl(wechatUser.getAvatarUrl());
        } else {
            comment.setNickName("匿名用户");
        }
        if (comment.getPics() != null && !comment.getPics().isEmpty()) {
            comment.setPicsArray(comment.getPics().split(","));
        } else {
            comment.setPicsArray(new String[]{});
        }
        // 获取总回复数
        BizComments replyComments = new BizComments();
        replyComments.setParentId(comment.getId());
        List<BizComments> replyList = bizCommentsService.selectBizCommentsList(replyComments);
        // 获取总点赞数
        BizCommentsLike like = new BizCommentsLike();
        like.setCommentId(comment.getId());
        List<BizCommentsLike> likeList = bizCommentsLikeService.selectBizCommentsLikeList(like);

        return AjaxResult.success()
                .put("comment", comment)
                .put("replyCount", replyList != null ? replyList.size() : 0)
                .put("likeCount", likeList != null ? likeList.size() : 0);
    }

    //发布评论
    @ApiOperation("发布评论")
    @Anonymous
    @PostMapping("/publishComment")
    public AjaxResult publishComment(@RequestBody BizComments bizComments
    ) {
        if (bizComments.getWechatUserId() == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        if (bizComments.getObjectId() == null) {
            return AjaxResult.error("评论对象ID不能为空");
        }
        if (bizComments.getContent() == null || bizComments.getContent().isEmpty())
        {
            return AjaxResult.error("评论内容不能为空");
        }
        if (bizComments.getType().equals("1")) {
            if (bizComments.getTitle() == null || bizComments.getTitle().isEmpty()) {
                return AjaxResult.error("评论标题不能为空");
            }
        }
        if (bizComments.getType().equals("2")) {
            if (bizComments.getParentId() == null) {
                return AjaxResult.error("评论楼主不能为空");
            }
        }
        // 内容安全校验
        String appId = "wx2947d889afa0bf74"; // 推荐用@Value注入
        String appSecret = "bd3a700248068cc185bc3a68ba91e1ae";
        String accessToken = WxContentSecurityUtil.getAccessToken(appId, appSecret);
        boolean safe = WxContentSecurityUtil.checkText(accessToken, bizComments.getContent());
        if (!safe) {
            return AjaxResult.error("评论内容不安全，请修改后再提交！");
        }
        WechatUser wechatUser = wechatUserService.selectWechatUserById(bizComments
                .getWechatUserId());
        if (wechatUser == null) {
            return AjaxResult.error("用户不存在");
        }
        bizComments.setCreatedAt(new Date());
        int result = bizCommentsService.insertBizComments(bizComments);
        if (result > 0) {
            if (bizComments.getType().equals("2")) {
                //发送消息notiy
                //查询楼主回复
                BizComments parentComment = bizCommentsService.selectBizCommentsById(bizComments.getParentId());
                if (parentComment == null) {

                }else{
                    //给被回复用户发送消息
                    WechatNotifyRemind notifyRemind = new WechatNotifyRemind();
                    notifyRemind.setUserId(parentComment.getWechatUserId());
                    notifyRemind.setObjectId(bizComments.getParentId());
                    notifyRemind.setSenderId(bizComments.getWechatUserId());
                    notifyRemind.setSenderName(wechatUser.getNickname());
                    notifyRemind.setSenderAction("回复了您的评论");
                    IWechatNotifyRemindService.insertWechatNotifyRemind(notifyRemind);
                }
            }
            return AjaxResult.success("评论发布成功");
        } else {
            return AjaxResult.error("评论发布失败");
        }
    }

    //uploadFile
//发布评论
    @ApiOperation("发布评论")
    @Anonymous
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }
        String fileUrl = "";
        try {
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            fileUrl = FileUploadUtils.upload(filePath, file);

            // 微信图片内容安全检测
            String appId = "wx2947d889afa0bf74"; // 推荐用@Value注入
            String appSecret = "bd3a700248068cc185bc3a68ba91e1ae";
            String accessToken = WxContentSecurityUtil.getAccessToken(appId, appSecret);
            boolean safe = WxContentSecurityUtil.checkMedia(accessToken, fileUrl, 2); // 2:图片
            if (!safe) {
                return AjaxResult.error("图片内容不安全，请更换后再上传！");
            }
        } catch (IOException e) {
            return AjaxResult.error().put("message", "上传失败");
        }
        return AjaxResult.success().put("fileUrl", fileUrl);
    }

    //删除评论
    @ApiOperation("删除评论")
    @Anonymous
    @GetMapping("/deleteComment")
    public AjaxResult deleteComment(@RequestParam Long id) {
        BizComments bizComments = bizCommentsService.selectBizCommentsById(id);
        if (bizComments == null) {
            return AjaxResult.error("评论不存在");
        }
        int result = bizCommentsService.deleteBizCommentsById(id);
        if (result > 0) {
            return AjaxResult.success("评论删除成功");
        } else {
            return AjaxResult.error("评论删除失败");
        }
    }
    //用户点赞
    //type 1 点赞 0 取消点赞
    @ApiOperation("用户点赞")
    @Anonymous
    @GetMapping("/likeComment")
    public AjaxResult likeComment(@RequestParam Long commentId,@RequestParam Long wechatUserId,@RequestParam int type) {
        if (wechatUserId == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        if (commentId == null) {
            return AjaxResult.error("评论ID不能为空");
        }
        WechatUser wechatUser = wechatUserService.selectWechatUserById(wechatUserId);
        if (wechatUser == null) {
            return AjaxResult.error("用户不存在");
        }
        BizComments comment = bizCommentsService.selectBizCommentsById(commentId);
        if (comment == null) {
            return AjaxResult.error("评论不存在");
        }
        //检查是否已经点赞
        BizCommentsLike like = new BizCommentsLike();
        like.setWechatUserId(wechatUserId);
        like.setCommentId(commentId);
        List<BizCommentsLike> likeList = bizCommentsLikeService.selectBizCommentsLikeList
                (like);
        if (type == 1) {
            if (likeList != null && likeList.size() > 0) {
                return AjaxResult.error("您已点赞");
            }
            BizCommentsLike bizCommentsLike = new BizCommentsLike();
            bizCommentsLike.setCommentId(commentId);
            bizCommentsLike.setWechatUserId(wechatUserId);
            bizCommentsLike.setCreatedAt(new Date());
            int result = bizCommentsLikeService.insertBizCommentsLike(bizCommentsLike);
            if (result > 0) {
                //给被点赞用户发送消息
                WechatNotifyRemind notifyRemind = new WechatNotifyRemind();
                notifyRemind.setUserId(comment.getWechatUserId());
                notifyRemind.setObjectId(commentId);
                notifyRemind.setSenderId(wechatUserId);
                notifyRemind.setSenderName(wechatUser.getNickname());
                notifyRemind.setSenderAction("点赞了您的评论");
                IWechatNotifyRemindService.insertWechatNotifyRemind(notifyRemind);
                return AjaxResult.success("点赞成功");
            } else {
                return AjaxResult.error("点赞失败");
            }
        } else {
            if (likeList == null || likeList.size() == 0) {
                return AjaxResult.error("您还未点赞");
            }
            int result = bizCommentsLikeService.deleteBizCommentsLikeById(likeList.get(0).getId());
            if (result > 0) {
                return AjaxResult.success("取消点赞成功");
            } else {
                return AjaxResult.error("取消点赞失败");
            }
        }
    }
}